/**
 * 本地测试组件合并工具
 * 用于在开发阶段将 LOCAL_TEST_COMPONENTS 合并到菜单中
 * @author AI Assistant
 * @date 2025-11-10
 */

import { LOCAL_TEST_COMPONENTS } from '@/constants/constants';

interface ComponentItem {
  componentCode?: string;
  [key: string]: any;
}

interface SubGroupItem {
  groupId?: number;
  groupName?: string;
  thumbnail?: string;
  componentList?: ComponentItem[];
}

interface GroupItem {
  groupId?: number;
  groupName?: string;
  groupCode?: string;
  thumbnail?: string;
  subGroupList?: SubGroupItem[];
}

/**
 * 深拷贝子分组
 */
const cloneSubGroup = (sub: SubGroupItem): SubGroupItem => ({
  ...sub,
  componentList: [...(sub.componentList || [])],
});

/**
 * 深拷贝分组
 */
const cloneGroup = (group: GroupItem): GroupItem => ({
  ...group,
  subGroupList: (group.subGroupList || []).map(cloneSubGroup),
});

/**
 * 合并本地测试组件到现有组件列表
 * @param originList 原始组件列表（来自API）
 * @returns 合并后的组件列表
 */
export const mergeLocalComponents = (originList: GroupItem[] = []): GroupItem[] => {
  // 如果没有本地测试组件，直接返回原始列表
  if (!LOCAL_TEST_COMPONENTS || LOCAL_TEST_COMPONENTS.length === 0) {
    return originList;
  }

  // 深拷贝原始列表，避免修改原数据
  const cloned = originList.map(cloneGroup);

  // 合并本地组件到现有列表
  LOCAL_TEST_COMPONENTS.forEach((localGroup) => {
    // 通过 groupCode 或 groupName 查找现有分组
    const targetGroup = cloned.find(
      (group) => group.groupCode === localGroup.groupCode || group.groupName === localGroup.groupName,
    );

    if (targetGroup) {
      // 如果找到现有分组，合并子分组
      localGroup.subGroupList?.forEach((localSub) => {
        const targetSub = targetGroup.subGroupList?.find((sub) => sub.groupName === localSub.groupName);

        if (targetSub) {
          // 如果找到现有子分组，添加组件
          const existCodes = new Set((targetSub.componentList || []).map((item) => item.componentCode));
          (localSub.componentList || []).forEach((comp) => {
            if (!existCodes.has(comp.componentCode)) {
              targetSub.componentList = [...(targetSub.componentList || []), { ...comp }];
              existCodes.add(comp.componentCode);
            }
          });
        } else {
          // 如果没有找到子分组，添加新子分组
          targetGroup.subGroupList = [...(targetGroup.subGroupList || []), cloneSubGroup(localSub)];
        }
      });
    } else {
      // 如果没有找到分组，添加新分组
      cloned.push(cloneGroup(localGroup));
    }
  });

  return cloned;
};

/**
 * 检查组件是否为本地AI组件
 */
export const isLocalAIComponent = (componentType: string): boolean => {
  return LOCAL_TEST_COMPONENTS.some((group) =>
    group.subGroupList.some((subGroup) =>
      subGroup.componentList.some((component) => component.componentCode === componentType)
    )
  );
};

export default mergeLocalComponents;
